package com.duapk.search.work;

import java.io.IOException;

import org.apache.lucene.search.IndexSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.duapk.search.constant.Constant;
import com.duapk.search.util.IOUtils;

/**
 * 关闭索引查询对象的线程
 * 
 * @Package: com.duapk.search.work
 * @ClassName: SearcherCloseWork
 * @author: jiangzheng
 * @date: Apr 5, 2011 4:55:36 PM
 * 
 */
public class SearcherCloseWork extends Thread {

	private static Logger logger = LoggerFactory
			.getLogger(SearcherCloseWork.class);

	private IndexSearcher searcher;

	private String indexPath;

	private String newIndexPath;

	public SearcherCloseWork(IndexSearcher searcher, String indexPath,
			String newIndexPath) {
		this.searcher = searcher;
		this.indexPath = indexPath;
		this.newIndexPath = newIndexPath;
	}

	@Override
	public void run() {
		// 等待10秒后进行旧的索引对象的删除
		try {
			Thread.sleep(Constant.SEARCH_TIME_OUT * 1000L);
		} catch (InterruptedException e) {
			// 不处理
		}

		// 关闭旧的索引查询对象
		closeSearcher(searcher);
		// 删除旧的索引目录
		if (indexPath != null && !indexPath.equals(newIndexPath)) {
			IOUtils.deleteFolder(indexPath);
		}

	}

	/**
	 * 关闭索引查询对象
	 * 
	 * @param oldSearcher
	 */
	private static void closeSearcher(IndexSearcher searcher) {
		if (searcher != null) {
			try {
				searcher.getIndexReader().directory().close();
				searcher.getIndexReader().close();
				searcher.close();
			} catch (IOException e) {
				logger.error("close searcher error.", e);
			} finally {
				searcher = null;
			}
		}
	}
}
